1
Beyond the NULL Trap
AI013 Lesson 2
00:00

The transition from C-style macros to C++ type-safe literals represents a fundamental shift in language usability, resolving the "NULL Trap" where zero-macro ambiguity causes silent logical errors.

1. The Overload Resolution Failure

In legacy standards (C++98), NULL is often defined as 0. When passed to overloaded functions, the compiler resolves NULL as an integer. This is evidenced by:

if (std::is_same<decltype(NULL), decltype(0)>::value)
    std::cout << "NULL is an int";

2. The nullptr Solution

C++11 introduced nullptr, a keyword of type std::nullptr_t. Unlike the macro, it cannot be implicitly converted to an integral type (except bool), ensuring pointer-specific overloads are selected.

The Legacy Trapfoo(NULL)Calls foo(int)The Modern Fixfoo(nullptr)Calls foo(char*)

3. Linkage & Interoperability

Modern C++ requires extern "C" to prevent name mangling when linking with C code (e.g., compiled with gcc). Maintaining type-safe pointers at this boundary is critical.

$$\text{std::nullptr\_t} \neq \text{int}$$

main.py
TERMINAL bash — 80x24
> Ready. Click "Run" to execute.
>